<!DOCTYPE html>
<%@ page language="java" import="com.compuvest.web.*,java.util.*,java.text.DecimalFormat,java.io.FileNotFoundException,com.amazon.payments.*,com.amazon.payments.model.*" pageEncoding="UTF-8" %>

<jsp:useBean id="sb" class="SQLBean" scope="application"/>
<jsp:useBean id="advertShow" class="AdvertShow" scope="application"/>
<jsp:useBean id="basket" class="Basket" scope="session"/>
<%!
    Items basketItems = new Items(); // for getResellerPriceLine()

    Address getShippingAddress(String purchaseContractId, AdvertShow advert) {

        Address address = new Address();
        try {
            //Create the Amazon Library Object
            CBAPurchaseContract lib = new CBAPurchaseContract();

            //Create an object of Shipping Address which will hold the address returned by getAddress call
            ShippingAddress shippingAddressRes = new ShippingAddress();

            //Call the Library function getAddress to get the address selected by the buyer
            List<ShippingAddress> shippingAddressList;

            shippingAddressList = lib.getAddress(purchaseContractId);

            //Displays all the selected address
            String zip, usastate;
            Iterator<ShippingAddress> shippingAddressIterator = shippingAddressList.iterator();
            while(shippingAddressIterator.hasNext()) {
                shippingAddressRes = (ShippingAddress) shippingAddressIterator.next();

                zip = shippingAddressRes.getPostalCode();
                zip = (zip == null) ? "" : zip;

                address.setCity(shippingAddressRes.getCity());
                address.setZip(zip.substring(0, (zip.indexOf('-') > 0 ? zip.indexOf('-') : zip.length())));
                address.setZip4(zip.substring((zip.indexOf('-') > 0 ? zip.indexOf('-') + 1 : zip.length()), zip.length()));

                usastate = shippingAddressRes.getStateOrProvinceCode();
                System.out.println("AmazonPaymant.jsp usastate="+usastate+" country="+shippingAddressRes.getCountryCode());
                if(usastate == null) {
                    usastate = "International";
                }
                else {
                    usastate = usastate.length() > 2 ? advert.getUsaState(usastate) : usastate;
                }

                address.setState(usastate);
                //address.setState(shippingAddressRes.getStateOrProvinceCode());
                address.setCountry(shippingAddressRes.getCountryCode());
            }
        } //Catch the internal exceptions
        catch(CheckoutByAmazonServiceException ex) {
            System.out.println(
                "\nService Exception: " + ex.getMessage() +
                "\nResponse Status Code: " + ex.getStatusCode() +
                "\nError Code: " + ex.getErrorCode() +
                "\nError Type: " + ex.getErrorType() +
                "\nRequest ID: " + ex.getRequestId() +
                "\nXML: " + ex.getXML());
        } //Catch the request exceptions which will come when there is some error in the inputs passed while calling the API
        catch(CheckoutByAmazonServiceRequestException ex) {
            System.out.println(
                "\nRequest Exception: " + ex.getMessage() +
                "\nResponse Status Code: " + ex.getStatusCode() +
                "\nError Code: " + ex.getErrorCode() +
                "\nError Type: " + ex.getErrorType() +
                "\nRequest ID: " + ex.getRequestId() +
                "\nXML: " + ex.getXML());
        } //Catch the exceptions which will come when properties file is not found
        catch(FileNotFoundException ex) {
            System.out.println("File not found Exception: " + ex.getMessage());
        }

        return address;
    }
%>
<%
    DecimalFormat priceForm = new DecimalFormat("$#,##0.00");

    String amazonId = basket.getAmazonId();

    Address userAddress = getShippingAddress(amazonId, advertShow);

    // shipping
    //basket.setShippingCost(advertShow.getDouble(request.getParameter("spb"), 0d));

    // tax
    basket.setTaxCost("WA".equalsIgnoreCase(userAddress.getState()) ? basket.roundTwoDecimals(basket.getTotal(true) * basket.WA_TAX_FEE) : 0d);

    //basket.setPaymentMethod(advertShow.getString(request.getParameter("payMethod"), ""));
%>
<html>
<head>
<title><%= application.getInitParameter("CompanyName") %></title>
<%@include file="./incl/scripts.txt" %>
<script type='text/javascript' src='https://static-na.payments-amazon.com/cba/js/us/PaymentWidgets.js'></script>
</head>
<body>

<div style="margin:10px 20px;">

   <%-- shopping cart --%>
<%
    if(basket.notEmpty()) {
%>
   <br/>
   <div class='htlt'>Shopping Cart</div>
   <table style='background-color:white;border:1px solid #d4d4d4;width:70%;font-size:12px;font-weight:bold;' border="1">
   <colgroup><col width='12%'/><col width='54%'/><col width='10%'/><col width='6%'/><col width='6%'/><col width='10%'/></colgroup>
    <tr class='bsm' height='26'><th>Part #</th><th>Product Name</th><th>Price</th><th>Stock</th><th>Qty</th><th>Amount</th></tr>
<%
	boolean ground = false;
	String rowspan = "";
	for(ItemsInBasket item : basket.getContents()) {
	    rowspan = (item.getWarrantyMask() & item.EXTENDED_WARRANTY) != 0 ? "rowspan='2'" : "";
%>
    <tr style='background-color:#ffff<%= (ground = !ground) ? "df" : "ff" %>;text-align:center;'>
     <td <%= rowspan %> id='nowrap'><%= item.getAccwareCode() %><div style='font-size:10px;color:blue;'><%= item.getCondition() %></div></td>
     <td style="text-align:left;padding:1px 5px;">
     <a href="javascript:;" class='tlink'><%= item.getItemName() %></a>
      <%= basket.getReseller() ? "<br/>" + basketItems.getResellerPriceLine(item) : "" %>
      <%= item.getPromotionPriceString(false) %>
     </td>
     <td>
<%	if(basket.getReseller() && item.getResPrice1() != 0d) { %>
      <div class='prices'><%= priceForm.format(item.getPrice()) %></div>
<%	} %>
     <%= priceForm.format(item.getSellPrice()) %><br/>
     </td>
     <td <%= rowspan %>><%= item.getStock() ? "Yes" : Integer.toString(item.getQuantity()) %></td>
     <td <%= rowspan %>><%= item.getTotalQuantity() %></td>
     <td><%= priceForm.format(item.getSellPrice() * item.getTotalQuantity()) %></td>
    </tr>
<%
	    // warranty &&  extended warranty any bit up ?
	    if((item.getWarrantyMask() & item.EXTENDED_WARRANTY) != 0) {
%>
    <tr style='background-color:#ffff<%= ground ? "df" : "ff" %>;text-align:center;'>
     <td style="text-align:left;padding:1px 5px;">
      <div style='font-size:10px;'>Warranty : <%= item.getWarrantyDays() %>.</div>
<%
    if(item.getWarrantyTotal() != 0d) {
%>
      <span id='wty' class='tipz'>Extended warranty <%= item.getWarrantyDesc() %> : <%= priceForm.format(item.getWarrantyTotal()) %></span>
<%
    }
%>
     </td>
     <td><%= item.getWarrantyPrice() == 0d ? "" : priceForm.format(item.getWarrantyPrice()) %></td>
     <td><%= item.getWarrantyPrice() == 0d ? "" : priceForm.format(item.getWarrantyTotal()) %></td>
    </tr>
<%
	    }
	}
%>
    <tr height='28'>
     <td colspan='7' style='padding-right:35px;text-align:right;vertical-align:middle;'>
      <font color='red'><%= basket.getCouponMessage(true) %></font><br/>
       Total Amount : <%= priceForm.format(basket.getTotal(true)) %>
      </td>
    </tr>
   </table>

   <table background='../img/it/tbg.png' style='width:70%;'>
    <tr><td width='100%' height='30'>&nbsp;</td></tr>
   </table>
<%
    } //(basket.notEmpty())
%>
   <%-- shopping cart --%>
<br/>
<div class='htlt'>Select your Payment  Method !</div>

<div id="AmazonWalletWidget"></div>
<script type='text/javascript' >
new CBA.Widgets.WalletWidget({
    merchantId: 'A3S3XOO7JN6CF5',
    displayMode: 'Edit',
    design:{size: { width:'400', height:'228' } },
    onPaymentSelect: function() {
        document.getElementById("Continue").disabled = false;
        document.getElementById("Continue").value = "Submit Order";
    }
}).render("AmazonWalletWidget");
</script>
<%--
<ul>
    <li><%= userAddress.getState() %></li>
    <li><%= userAddress.getCountry() %></li>
    <li><%= userAddress.getZip() %></li>
    <li><%= userAddress.getZip4() %></li>
    <li><%= basket.getTaxCost() %></li>

</ul>
--%>
<br/>

<div class='htlt'>Shipping Method</div>
<form id="apayment" action='<%= application.getInitParameter("https") %>AmazonDone.jsp' method='POST'>
<%

    ArrayList<ShipRate> shippRate;
    if("US".equals(userAddress.getCountry())) {
        shippRate = sb.getShippingChartUS(userAddress.getZip(), basket.getTotalWeight());
    }
    else {
        shippRate = sb.getShippingChart(userAddress.getCountry(), basket.getTotalWeight());
    }

    boolean oneTime = true;
    String groundLine;
    for(ShipRate ship : shippRate) {
        groundLine = new DecimalFormat("$#,##0.00").format(ship.getShipPrice()) + " - " + ship.getDescription();
        // if amazon free shipping (fdg == ground)
        //if("fdg".equals(ship.getShipCode())) {
        //    ship.setShipPrice(0d, 0d);
        //    groundLine = ShipRate.STR_FREE_SHIPPING;
        //}
        if("fdg".equals(ship.getShipCode())) {
            String advName = basket.getCompuvestCookies().getAdvertSite();
            if(advertShow.isFreeShipping(advName)) {
            //if(advName.contains("oogle") ||
            //    advertShow.getAdvertID(advName) == AdvertShow.ADV_CWS ||
            //    advertShow.getAdvertID(advName) == AdvertShow.ADV_CWM ||
            //    advertShow.getAdvertID(advName) == AdvertShow.BING) {

                ship.setShipPrice(0d, 0d);
                groundLine = ShipRate.STR_FREE_SHIPPING;
            }
        }
%>
       <input type='radio' name='ship' value='<%= ship.getShipPrice() + ":" + ship.getShipCode() + ":" + ship.getDescription() %>' <%= oneTime ? "checked='checked'" : "" %> /><%= groundLine %><br/>
<%
        oneTime = false;
    }
%>
<br/><br/>
 <div>
 <input type="button" value="Select Credit Card" id="Continue" onClick="document.id('apayment').submit();" disabled="true" class='abutt'/>
 &nbsp;&nbsp;&nbsp;<img src="../img/amzwarn.png" alt="" style=""/>
 </div>
</form>
</div>

</body>
<script type='text/javascript' >
var img = new Image();
img.src = (("http:" === document.location.protocol) ? "http://" : "https://") + 'www.compuvestb2b.com/WebStatus/amazon?pg=2';
</script>

</html>
